package com.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.common.utils.Result;
import com.entity.Card;
import com.entity.TaskStore;
import com.query.CardQuery;
import com.service.CardService;
import com.service.TaskStoreService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
@RestController
@RequestMapping("/card")
public class CardController {

    @Autowired
    private CardService cardService;

    @Autowired
    private TaskStoreService taskStoreService ;

    /**
     * 添加卡片，根据条件添加卡片
     */
    @RequestMapping("/addCard")
    public Result addCard(@RequestBody CardQuery cardQuery){
        return cardService.addCard(cardQuery);
    }

    /**
     * 删除卡片
     */
    @RequestMapping("/delCard/{id}")
    public Result delCard(@PathVariable Integer id){
        boolean falg = cardService.deleteById(id);
        if(falg){
            return  Result.success("删除成功");
        }else{
            return  Result.error("删除失败");
        }
    }

    /**
     * 根据卡片id获取卡片信息
     */
    @RequestMapping("/getCardById/{id}")
    public Result getCardById(@PathVariable Integer id){
        Card card = cardService.selectById(id);
        return  Result.success(card);
    }

    /**
     * 编辑卡片
     */
    @RequestMapping("/editCard")
    public  Result editCard(@RequestBody CardQuery cardQuery){
        Card card=new Card();
        BeanUtils.copyProperties(cardQuery,card);
        boolean falg = cardService.updateById(card);
        if(falg){
            return  Result.success("编辑成功");
        }else{
            return  Result.error("编辑失败");
        }
    }

    /**
     * 根据条件获取卡片列表
     */
    @RequestMapping("/getCardList")
    public Result getCardList(@RequestBody CardQuery cardQuery){
        return cardService.getCardList(cardQuery);
    }

    /**
     * 根据任务获取卡片
     */
    @RequestMapping("/getCradListByTaskId/{id}")
    public Result getCradListByTaskId(@PathVariable Integer id){
        Wrapper<TaskStore> wr=new EntityWrapper<>();
        wr.eq("id",id);
        TaskStore taskStore = taskStoreService.selectOne(wr);
        if(null==taskStore){
            return  Result.success();
        }else{
            String cardId = taskStore.getCardId();
            if(!StringUtils.isEmpty(cardId)){
                List<String> strings = JSONArray.parseArray(cardId, String.class);

                Wrapper<Card> cwr=new EntityWrapper<>();
                cwr.in("id",strings);
                List<Card> cards = cardService.selectList(cwr);
                return  Result.success(cards);
            }else{
                return  Result.success();
            }
        }

    }


}
